const mongoose = require("mongoose")
const db = 'mongodb://localhost/douban-trailer'
const glob = require("glob")
const {resolve} = require("path")
mongoose.Promise = global.Promise

exports.initSchema=()=>{
    glob.sync(resolve(__dirname,"./schema","**/*.js")).forEach(require)
}

exports.connect = () => {

    let maxConnectTimes = 0
    return new Promise((resolve, reject) => {
        if (process.env.NODE_ENV !== 'production') {
            //判断是不是生产环境
            mongoose.set('debug', true)
        }
        mongoose.connect(db,{useNewUrlParser:true})

        mongoose.connection.on('disconnect', () => {
            if (maxConnectTimes < 5) {
                maxConnectTimes = maxConnectTimes + 1
                mongoose.connect(db,{useNewUrlParser:true})
            }
            else {
                throw new Error('数据库挂了 快去修')
            }
        })
        mongoose.connection.on('error', err => {
            reject(err)
            console.log(err)
        })
        mongoose.connection.once('open', () => {
            // const Cat = mongoose.model("Cat",{
            //     name:String,
            // })
            // const cat = new Cat({name:'jiangshanshan'})
            // cat.save().then(()=>{
            //     console.log("miao")
            // })
            resolve()
            console.log('mongodb connected succ')
        })

    })


}
